package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 宿舍 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-03-02
 */
@RestController
@RequestMapping("/api/admin/dormRoom")
public class DormRoomController extends BaseController{

    @Autowired
    IDormRoomService iDormRoomService;
    @Autowired
    IDormRoomMemberService iDormRoomMemberService;
    @Autowired
    IDormManagerHisService iDormManagerHisService;
    @Autowired
    IDormRoomMemberHisService iDormRoomMemberHisService;
    @Autowired
    IStaffService iStaffService;
    @Autowired
    IDictService iDictService;
    @Autowired
    IAreaService iAreaService;

    //获取宿舍长
    @GetMapping("/getDormRoomStaff")
    public Result getDormRoomStaff(@RequestParam(value = "id", defaultValue = "") String id){


        LocalDate currentDate = LocalDate.now();
        QueryWrapper<DormRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        // 查询pact_end_date_time大于等于当前时间的记录
        queryWrapper.ge("pact_end_date_time", currentDate);
        List<DormRoom> dormRoomList = iDormRoomService.list(queryWrapper);
        //获取所有id
        List<Long> roomIdList = dormRoomList.stream().map(DormRoom::getId).collect(Collectors.toList());
        String roomIds = roomIdList.stream().map(String::valueOf).collect(Collectors.joining(","));

        List<DormRoom> dormRoomManagerList = null;

        if (StringUtils.isBlank(id)) {
            dormRoomManagerList = iDormRoomService.getDormRoomManagerList(roomIds);
        } else {
            dormRoomManagerList = iDormRoomService.getDormRoomManagerListById(id);
        }

        return new Result(Code.OK, dormRoomManagerList, Code.GET_OK_MSG);

    }


    @GetMapping("/getDormRoomList")
    public Result getDormRoomList(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                  @RequestParam(value = "areaId", defaultValue = "") String areaId,
                                  @RequestParam(value = "sexType", defaultValue = "") String sexType,
                                  @RequestParam(value = "status", defaultValue = "") String status,
                                  @RequestParam(value = "name", defaultValue = "") String name,
                                  @RequestParam(value = "dueStatus", defaultValue = "") String dueStatus  //到期状态 0正常 1快到期 2已到期
    ){
        IPage<DormRoom> iPage = new Page<>(pageNum, pageSize);
        // 获取当前时间
        LocalDate currentDate = LocalDate.now();
/*        if (StringUtils.isNotBlank(dueStatus)){
            if (dueStatus.equals("0") || dueStatus.equals("1")){
                 currentDate = currentDate.plusMonths(3);
            }
        }*/
        IPage<DormRoom> dormRoomList = iDormRoomService.getDormRoomList(iPage, areaId, sexType, status, name, dueStatus, currentDate);
        for (DormRoom dormRoom : dormRoomList.getRecords()){

            QueryWrapper<Area> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", dormRoom.getAreaId());
            queryWrapper.eq("status", 1);
            queryWrapper.eq("deleted", 0);
            Area area = iAreaService.getOne(queryWrapper);
            if (area != null) {
                dormRoom.setAreaName(area.getName());
            }
            QueryWrapper<DormRoomMember> queryWrapperDormRoomMember = new QueryWrapper<>();
            queryWrapperDormRoomMember.eq("room_id", dormRoom.getId());
            long count = iDormRoomMemberService.count(queryWrapperDormRoomMember);
            dormRoom.setLiveCount((int) count);   //已住数量
            dormRoom.setNotLiveCount(dormRoom.getBerth() - dormRoom.getLiveCount());  //剩余数量

            LocalDate currentDate1 = LocalDate.now();
            if (currentDate1.isAfter(dormRoom.getPactEndDateTime())) {
                dormRoom.setDue("已到期");
                dormRoom.setDueStatus(2);
            } else if (!currentDate1.plusMonths(3).isBefore(dormRoom.getPactEndDateTime())) {
                dormRoom.setDue("快到期");
                dormRoom.setDueStatus(1);
            } else {
                dormRoom.setDue("正常");
                dormRoom.setDueStatus(0);
            }
        }
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    @PostMapping("/saveDormRoom")
    public Result saveDormRoom(@RequestBody DormRoom dormRoom){

        dormRoom.setCreatedId(this.adminId);
        boolean save = iDormRoomService.save(dormRoom);

        if (save){
            //获取系统当前时间
            LocalDate currentDate = LocalDate.now();
            DormManagerHis dormManagerHis = new DormManagerHis();
            dormManagerHis.setRoomId(dormRoom.getId());
            dormManagerHis.setManagerId(dormRoom.getManagerId());
            dormManagerHis.setStartDate(currentDate);
            dormManagerHis.setCreatedId(this.adminId);
            iDormManagerHisService.save(dormManagerHis);
            return new Result(Code.SAVE_OK, "", "保存成功");
        }
        return new Result(Code.SAVE_ERROR, "", "保存失败");
    }

    @DeleteMapping("/deleteDormRoom")
    public Result deleteDormRoom(@RequestBody DormRoom dormRoom){
        DormRoom dormRoom1 = iDormRoomService.getById(dormRoom.getId());
        if (dormRoom1 == null){
            return new Result(Code.EXP_ERROR, "", "该宿舍不存在，无法删除");
        }

        QueryWrapper<DormRoomMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_id", dormRoom.getId());
        long count = iDormRoomMemberService.count(queryWrapper);
        if (count > 0){
            return new Result(Code.DELETE_ERROR, "", "该此宿舍有宿舍成员，不可删除");
        }

        boolean remove = iDormRoomService.removeById(dormRoom.getId());
        if (remove){
            return new Result(Code.DELETE_OK, "", "删除成功");
        }
        return new Result(Code.DELETE_ERROR, "", "删除失败");
    }

    @PutMapping("/updateDormRoom")
    public Result updateDormRoom(@RequestBody DormRoom dormRoom){
        DormRoom existingDormRoom = iDormRoomService.getById(dormRoom.getId());
        if (existingDormRoom == null){
            return new Result(Code.EXP_ERROR, "", "该宿舍不存在，无法编辑");
        }
        // 比较 managerId 是否发生变化
        boolean managerIdChanged = !existingDormRoom.getManagerId().equals(dormRoom.getManagerId());

        boolean update = iDormRoomService.updateById(dormRoom);
        if (update){
            if (managerIdChanged) {
                // 获取系统当前时间
                LocalDate currentDate = LocalDate.now();

                // 检查是否存在当天的记录
                QueryWrapper<DormManagerHis> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("room_id", dormRoom.getId());
//                queryWrapper.eq("created_id", this.adminId);
                queryWrapper.eq("start_date", currentDate);
                List<DormManagerHis> existingRecords = iDormManagerHisService.list(queryWrapper);
                if (!existingRecords.isEmpty()) {
                    // 存在当天的记录，删除这些记录
                    for (DormManagerHis record : existingRecords) {
                        iDormManagerHisService.removeById(record.getId());
                    }
                }


                DormManagerHis dormManagerHis = new DormManagerHis();
                dormManagerHis.setRoomId(dormRoom.getId());
                dormManagerHis.setManagerId(dormRoom.getManagerId());
                dormManagerHis.setStartDate(currentDate);
                //截止时间等于当前时间减一天
//                dormManagerHis.setEndDate(currentDate.minusDays(1));
                dormManagerHis.setCreatedId(this.adminId);
                iDormManagerHisService.save(dormManagerHis);

                // 更新上一条记录的截止时间
                QueryWrapper<DormManagerHis> previousRecordQuery = new QueryWrapper<>();
                previousRecordQuery.eq("room_id", dormRoom.getId());
                previousRecordQuery.ne("id", dormManagerHis.getId());
                previousRecordQuery.orderByDesc("start_date").last("LIMIT 1");
                DormManagerHis previousRecord = iDormManagerHisService.getOne(previousRecordQuery);

                if (previousRecord != null) {
                    previousRecord.setEndDate(currentDate.minusDays(1));
                    iDormManagerHisService.updateById(previousRecord);
                }

            }
            return new Result(Code.UPDATE_OK, "", "修改成功");
        }
        return new Result(Code.UPDATE_ERROR, "", "修改失败");
    }

    @GetMapping("/getDormRoomManageCount")
    public Result getDormRoomManageCount(){
        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<DormRoom> queryWrapperDormRoom = new QueryWrapper<>();
        queryWrapperDormRoom.eq("status", 1);
        long  dormRoomCount= iDormRoomService.count(queryWrapperDormRoom);
        map.put("dormRoomCount", dormRoomCount); // 宿舍数量

        QueryWrapper<DormRoomMember> queryWrapperDormRoomMember = new QueryWrapper<>();
        long dormRoomMemberCount = iDormRoomMemberService.count(queryWrapperDormRoomMember);
        map.put("dormRoomMemberCount", dormRoomMemberCount);  //已入住数量

        //查询男生总床位、剩余床位
        QueryWrapper<DormRoom> queryWrapperDormRoom1 = new QueryWrapper<>();
        queryWrapperDormRoom1.eq("sex_type", 1);
        queryWrapperDormRoom1.eq("status", 1);
        List<DormRoom> dormRoomList = iDormRoomService.list(queryWrapperDormRoom1);
        //获取dormRoomListid
        List<Long> dormRoomIdList = dormRoomList.stream().map(DormRoom::getId).collect(Collectors.toList());

        if (!dormRoomIdList.isEmpty()) {
            QueryWrapper<DormRoomMember> queryWrapperDormRoomMemberMan = new QueryWrapper<>();
            queryWrapperDormRoomMemberMan.in("room_id", dormRoomIdList);
            long dormRoomMemberManCount = iDormRoomMemberService.count(queryWrapperDormRoomMemberMan);
            int dormRoomManCount = dormRoomList.stream().mapToInt(DormRoom::getBerth).sum();
            int dormRoomMemberManNotCount = dormRoomManCount - (int) dormRoomMemberManCount;
            map.put("dormRoomManCount", dormRoomManCount);
            map.put("dormRoomMemberManNotCount", dormRoomMemberManNotCount);  // 男生剩余床位
        } else {
            map.put("dormRoomManCount", 0);
            map.put("dormRoomMemberManNotCount", 0);
        }

  /*      QueryWrapper<DormRoomMember> queryWrapperDormRoomMemberMan= new QueryWrapper<>();
        queryWrapperDormRoomMemberMan.in("room_id", dormRoomIdList);
        long dormRoomMemberManCount = iDormRoomMemberService.count(queryWrapperDormRoomMemberMan);
        int dormRoomManCount = 0;
        for (DormRoom dormRoom : dormRoomList) {
            dormRoomManCount += dormRoom.getBerth();
        }
        int dormRoomMemberManNotCount = (int) (dormRoomManCount - dormRoomMemberManCount);
        map.put("dormRoomManCount", dormRoomManCount);
//        map.put("dormRoomMemberManCount", dormRoomMemberManCount);
        map.put("dormRoomMemberManNotCount", dormRoomMemberManNotCount);  //男生剩余床位*/

        //查询女生总床位、剩余床位
        QueryWrapper<DormRoom> queryWrapperDormRoom2 = new QueryWrapper<>();
        queryWrapperDormRoom2.eq("sex_type", 0);
        queryWrapperDormRoom2.eq("status", 1);
        List<DormRoom> dormRoomList2 = iDormRoomService.list(queryWrapperDormRoom2);
        List<Long> dormRoomIdList2 = dormRoomList2.stream().map(DormRoom::getId).collect(Collectors.toList());

        if (!dormRoomIdList2.isEmpty()) {
            QueryWrapper<DormRoomMember> queryWrapperDormRoomMemberWoman = new QueryWrapper<>();
            queryWrapperDormRoomMemberWoman.in("room_id", dormRoomIdList2);
            long dormRoomMemberWomanCount = iDormRoomMemberService.count(queryWrapperDormRoomMemberWoman);
            int dormRoomWomanCount = dormRoomList2.stream().mapToInt(DormRoom::getBerth).sum();
            int dormRoomMemberWomanNotCount = dormRoomWomanCount - (int) dormRoomMemberWomanCount;
            map.put("dormRoomWomanCount", dormRoomWomanCount);
            map.put("dormRoomMemberWomanNotCount", dormRoomMemberWomanNotCount);  // 女生剩余床位
        } else {
            map.put("dormRoomWomanCount", 0);
            map.put("dormRoomMemberWomanNotCount", 0);
        }

  /*      QueryWrapper<DormRoomMember> queryWrapperDormRoomMemberWoman= new QueryWrapper<>();
        queryWrapperDormRoomMemberWoman.in("room_id", dormRoomIdList2);
        long dormRoomMemberWomanCount = iDormRoomMemberService.count(queryWrapperDormRoomMemberWoman);
        int dormRoomWomanCount = 0;
        for (DormRoom dormRoom : dormRoomList2) {
            dormRoomWomanCount += dormRoom.getBerth();
        }
        int dormRoomMemberWomanNotCount = (int) (dormRoomWomanCount - dormRoomMemberWomanCount);
        map.put("dormRoomWomanCount", dormRoomWomanCount);
        map.put("dormRoomMemberWomanNotCount", dormRoomMemberWomanNotCount);*/

        return new Result(Code.OK, map, Code.GET_OK_MSG);
    }

    @GetMapping("/getDormRoomDetails")
    public Result getDormRoomDetails(@RequestParam(value = "id", defaultValue = "") String id){
        DormRoom dormRoom = iDormRoomService.getById(id);
        if (dormRoom == null){
            return new Result(Code.ERROR, "", "该宿舍不存在");
        }

        QueryWrapper<Area> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", dormRoom.getAreaId());
        queryWrapper.eq("status", 1);
        queryWrapper.eq("deleted", 0);
        Area area = iAreaService.getOne(queryWrapper);
        if (area != null) {
            dormRoom.setAreaName(area.getName());
        }

        QueryWrapper<Staff> queryWrapperStaff = new QueryWrapper<>();
        queryWrapperStaff.eq("id", dormRoom.getManagerId());
        Staff staff = iStaffService.getOne(queryWrapperStaff);
        if (staff != null) {
            dormRoom.setStaffName(staff.getName());
        }

        QueryWrapper<DormRoomMember> queryWrapperDormRoomMember = new QueryWrapper<>();
        queryWrapperDormRoomMember.eq("room_id", dormRoom.getId());
        long count = iDormRoomMemberService.count(queryWrapperDormRoomMember);
        dormRoom.setLiveCount((int) count);   //已住数量
        dormRoom.setNotLiveCount(dormRoom.getBerth() - dormRoom.getLiveCount());  //剩余数量
        return new Result(Code.OK, dormRoom, Code.GET_OK_MSG);
    }

    //编辑宿舍成员获取宿舍名
    @GetMapping("/getDormRoomListBySexType")
    public Result getDormRoomListBySexType(@RequestParam(value = "SexType", defaultValue = "") String SexType //0女 1男
    ){
        // 获取当前时间
        LocalDate currentDate = LocalDate.now();
        QueryWrapper<DormRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sex_type", SexType);
        queryWrapper.eq("status", 1);
        // 查询pact_end_date_time大于等于当前时间的记录
        queryWrapper.ge("pact_end_date_time", currentDate);
        List<DormRoom> dormRoomList = iDormRoomService.list(queryWrapper);
        return new Result(Code.OK, dormRoomList, Code.GET_OK_MSG);

    }

}
